package com.sbtr.exception;

import com.alibaba.fastjson.JSON;
import com.sbtr.common.Response;
import com.sbtr.common.ResultCodeCanstant;

/**
 * 系统运行时异常基础
 *
 * @author qiujun
 * @date 2019-10-30
 */
public class BaseRuntimeException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	protected int code;
	protected String rawMessage;
	protected String rawData;

	public BaseRuntimeException(String message) {
		this(ResultCodeCanstant.SYSTEN_ERROR.getValue(), message);
	}

	public BaseRuntimeException(String message, Throwable e) {
		this(ResultCodeCanstant.SYSTEN_ERROR.getValue(), message, e);
	}

	public BaseRuntimeException(int code, String message) {
		super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}");
		this.code = code;
		this.rawMessage = message;
	}

	public BaseRuntimeException(int code, String message, String data) {
		super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\", \"data\": \"" + data + "\"}");
		this.code = code;
		this.rawMessage = message;
		this.rawData = data;
	}

	public BaseRuntimeException(int code, String message, Throwable e) {
		super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}", e);
		this.code = code;
		this.rawMessage = message;
	}

	public BaseRuntimeException(int code, String message, String data, Throwable e) {
		super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\", \"data\": \"" + data + "\"}", e);
		this.code = code;
		this.rawMessage = message;
		this.rawData = data;
	}

	public int getCode() {
		return this.code;
	}

	public String getRawMessage() {
		return this.rawMessage;
	}

	public String toRestResponseJson() {
		if (this.rawData != null) {
			return JSON.toJSONString(Response.error(this.code, this.rawMessage, this.rawData));
		} else {
			return JSON.toJSONString(Response.error(this.code, this.rawMessage));
		}
	}

	public static String getMessage(int code) {
		return ResultCodeCanstant.valueOf(code).getReasonPhrase();
	}

}
